<?php
namespace app\wx\controller;
use think\Db;
use think\Controller;
use think\Request;
use think\Config;
use org\wechat\Jssdk;


class Index extends Controller
{
	protected function _initialize(){
	
		//header ('Access-Control-Allow-Origin:http://localhost:8080');
		parent::_initialize();
        isset($_SERVER['HTTP_ORIGIN']) ? header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']) : '';
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, authKey, sessionId");
        $param =  Request::instance()->param();
        $this->param = $param;
	}
	//获取手机验证码
	public function getcode(){
		$request = Request::instance();
	
		$phone =$request->post('phone');
		$code = rand(1000,9999);
		$state = sendsms($phone,$code,"SMS_152715274","0");

		if($state=="1"){
			$data["mobile"]=$phone;
			$data["code"]=$code;
			$data["createtime"]= date('Y-m-d H:i:s',time());
		
			db('smslog')->insertGetId($data);

			$obj["status"]=200;
			$obj["message"]="发送成功";
			return json($obj);
		}else{
			$obj["status"]= 500;
			$obj["message"]="发送失败";
			return json($obj);
			
		}

	}
	//绑定学生
	public function bingstudent(){
		$request = Request::instance();
		$number =$request->post('number');
		$truename =$request->post('truename');
		$userid =$request->post('userid');
		$relation =$request->post('relation');

		$student = db('student')->where("number='".$number."' and truename='".$truename."'")->find();
		if($student){
			$studentandparent= db('studentandparent')->where("userid=".$userid." and studentid=".$student["id"])->find();

			$otherbind= db('studentandparent')->where("studentid=".$student["id"])->find();
			if($studentandparent){
				$obj["status"]=400;
				$obj["message"]="你已绑定该学生";
				return json($obj);

			}else if($otherbind){
				$obj["status"]=400;
				$obj["message"]="一个学生只能绑定一个微信号";
				return json($obj);

			}else{
				$data["userid"]=$userid;
				$data["studentid"]=$student["id"];
				$data["mid"]=$student["mid"];
				$data["relation"]=$relation;
				$data["createtime"]= date('Y-m-d H:i:s',time());
				$data["seq"]=1;

				$updatesql = 'update users set state=1,type=1,mid='.$student["mid"].',bindtime='.date('Y-m-d H:i:s',time()).' where id='.$userid;
				$updateresult = Db::execute('update users set state=1,type=1,mid=?,bindtime=? where id=?',[$student["mid"], date('Y-m-d H:i:s',time()),$userid]);

				file_put_contents("test.txt","updatesql".$updatesql.PHP_EOL,FILE_APPEND);

				if(db('studentandparent')->insertGetId($data)&&$updateresult){
					$obj["status"]=200;
					$obj["message"]="绑定成功";
					$obj["data"]=$student;
					return json($obj);
				}else{
					$obj["status"]=400;
					$obj["message"]="绑定失败";
					return json($obj);
				}

			}
			
		}else{
			$obj["status"]=400;
			$obj["message"]="没找到学生信息";
			return json($obj);
		}

	}
	public function studentsearch(){
		$request = Request::instance();
		$number =$request->post('number');
		$where = "student.number='".$number."' and student.state=0";
		if($truename!=""){
			$where=$where." and student.truename like '%".$truename."%'";
		}
		$truename =$request->post('truename');
		$student = db('student')->join("myclass","student.classid= myclass.id")->join("mechanism","mechanism.id=student.mid")->where($where)->field("student.*,myclass.classname,mechanism.name as mname")->find();
		if($student){
			$obj["status"]=200;
			$obj["message"]="success";
			$obj["data"]=$student;
			return json($obj);
		}else{
			$obj["status"]=500;
			$obj["message"]="没找到学生信息";
			return json($obj);
		}
	}
	public function bingteacher(){
		$request = Request::instance();
		$userid =$request->post('userid');
		$mid =$request->post('mid');

		//file_put_contents("test.txt","userid=".$userid.PHP_EOL,FILE_APPEND);

		$userinfo = db("users")->where("id=".$userid)->find();
		if($userinfo){
			$teacherinfo = db("teacher")->where("phone='".$userinfo["phone"]."'")->find();
			if($teacherinfo){
				
				$teacheranduser= db("teacheranduser")->where("userid=".$userid." and teacherid=".$teacherinfo["id"])->find();
				if($teacheranduser){
						$obj["status"]=500;
						$obj["message"]="已绑定";
						return json($obj);

				}else{
					$data["userid"]=$userid;
					$data["teacherid"]=$teacherinfo["id"];
					$data["mid"]=$mid;
					$data["createtime"]=date('Y-m-d H:i:s',time());
					$updateresult = Db::execute('update users set state=1,type=2,mid=?,bindtime=? where id=?',[$mid,date('Y-m-d H:i:s',time()),$userid]);

					if(db("teacheranduser")->insertGetId($data)&&$updateresult){
						$obj["status"]=200;
						$obj["message"]="绑定成功";
						$obj["data"]=$teacherinfo;
						return json($obj);

					}else{
						$obj["status"]=500;
						$obj["message"]="绑定失败";
						return json($obj);
					}


				

				}	

			}else{
				$obj["status"]=500;
				$obj["message"]="老师信息不存在";
				return json($obj);
			}


		
		}else{
			$obj["status"]=500;
			$obj["message"]="用户信息不存在";
			return json($obj);
		}
		

	}
	//首页
	public function gethome(){
		$request = Request::instance();
	
		$mid =$request->post('mid');
		$imagelist = db('imagelist')->where("state=1 and mid=".$mid)->order("seq asc")->limit(0,5)->select();
		$url =  $_SERVER["REQUEST_SCHEME"].'://'.$_SERVER["SERVER_NAME"].'/static/uploads/';
		
		$banner = [];
		$sys_pic= db("sys_pic")->where("typeid=1 and state=1")->select();
		foreach ($sys_pic as $key1 => &$value1) {
			$image["imgurl"]= $url.$value1["imgurl"];
			array_push($banner,$image);
		}
		foreach ($imagelist as $key => &$value) {
			$value["imgurl"]= $url.$value["imgurl"];
			array_push($banner,$value);
		}
			
		

		

		$mydate = date('Y-m-d',time());
		$foodlist = db('food')->where("mid=".$mid)->order("id asc")->limit(0,10)->select();
		$url =  $_SERVER["REQUEST_SCHEME"].'://'.$_SERVER["SERVER_NAME"].'/static/uploads/';
		$sys_pic = db("sys_pic")->where("typeid=2 and state=1")->order("id desc")->find();
		$defaulturl = $url.$sys_pic["imgurl"];

		foreach ($foodlist as $key => &$value) {
			if($value["imgurl"]!=""){
				$value["imgurl"]=$url.$value["imgurl"];
			}else{
				$value["imgurl"]=$defaulturl;
			}

			$result = Db::query('select avg(star) as star from foodstar where foodid=?',[$value["id"]]);
			$value["star"]=$result[0]["star"];
		}
		

		$newslist = db('news')->where("mid=".$mid)->order("id desc")->limit(0,10)->select();

		$obj["imagelist"]=$banner; 
		$obj["foodlist"]=$foodlist;
		$obj["newslist"]=$newslist;
		$obj["status"]=200;
		return json($obj);



	}

	//获取openid和头像昵称
	public function getuser()
	{	
	
		$appid=Config::get('appid');
		$secret=Config::get('secret');
		// access_token	调用接口凭证,这里通过code换取的是一个特殊的网页授权access_token,与基础支持中的access_token（该access_token用于调用其他接口）不同
		// openid	普通用户的标识，对当前公众号唯一
		//避免重复发送授权链接。已经获取用户信息，刷新页面，获得重新返回该页面，导致相同的授权链接再次请求，产生错误。
		//把获取的用户信息保存，每次发送请求前，检查是否已经获取，如果已经获取用户信息，就不再请求。
		//提示errcode":40163,"errmsg":"code been used。说明code被使用过一次了，code只能用一次。
		//判断是否发送获取code连接
		if(!$_GET["code"]){
			$url= "http://jiao.wulinkyun.com/wx/index/getuser";
			$url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=".$url."&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
			//发送GET请求
			header("Location: ".$url);
			exit();//必要
		}else{
			$url="http://jiaowx.wulinkyun.com?code=".$_GET["code"];
				//echo $url;
			header("Location: ".$url);
			exit();//必要
		
		 }
 

		
 
	
	}
	//获取access_token
	public function getaccess_token(){
		$request = Request::instance();
		$appid=Config::get('appid');
		$secret=Config::get('secret');
		$code= $request->post('code');
		
		//file_put_contents("test.txt","code".$code.PHP_EOL,FILE_APPEND);
				$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
            	$result=$this->request($url);
				if (!$result) {
					return false;
				}
			
				//echo $result;
				$arr=json_decode($result,true);		
				$openid=$arr['openid'];
				$access_token=$arr['access_token'];
				$url="https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
				$result=$this->request($url);

				//$openid="ouE7c0gLg3cgqsD365tjtd6DoTno";  //老师
			  //  $openid="ouE7c0hFU-KuTBszNDYS9Lwmk9fw";
			   
			//file_put_contents("test.txt","data".$result.PHP_EOL,FILE_APPEND);
				$arr=json_decode($result,true);	

				
				$where="openid='".$openid."'";

				$userinfo = db('users')->where($where)->find();
			
				if($userinfo){

					if($userinfo["mid"]){
						$mechanism = db("mechanism")->where("id=".$userinfo["mid"])->find();
						if($mechanism){
							$now=strtotime(date('Y-m-d H:i:s'));
							$endtime=strtotime($mechanism["endtime"]);
							if($endtime<$now){
								return json(['status'=>500,'message'=>'机构已到期','data'=>$userinfo]);
							}
							
						}else{
							return json(['status'=>500,'message'=>'机构不存在','data'=>$userinfo]);
						}
					}

					$userinfo["openid"]=$openid;
					$userinfo["nickname"]=$arr["nickname"];
					$userinfo["headimgurl"]=$arr["headimgurl"];
					if($userinfo["phone"]!=""){
							if($userinfo["state"]==1){
								if($userinfo["type"]=="1"){
									$studentandparent = db("studentandparent")->join("student","student.id=studentandparent.studentid")->where("studentandparent.userid=".$userinfo["id"]." and student.state=0")->find();
									if($studentandparent){
										$userinfo["studentid"]=$studentandparent["studentid"];
										$student = db("student")->where("id=".$userinfo["studentid"])->find();
										$userinfo["truename"]=$student["truename"];

									}else{
										return json(['status'=>200,'message'=>'未选择身份','data'=>$userinfo]);
									}
									

								}else if($userinfo["type"]=="2"){
									$teacheranduser = db("teacheranduser")->where("userid=".$userinfo["id"])->find();
									if($teacheranduser){
										$teacher = db("teacher")->where("id=".$teacheranduser["teacherid"])->find();

									//	$myclass = db("myclass")->where("id=".$teacheranduser["classid"])->find();
										
										$userinfo["truename"]= $teacher["teachername"];
										$userinfo["classname"]= "";
										$userinfo["teacherid"]= $teacher["id"];

									}else{
										return json(['status'=>200,'message'=>'未选择身份','data'=>$userinfo]);
									}
								}
								$mechanism = db("mechanism")->where("id=".$userinfo["mid"])->find();
								$type="";
								if(strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone')||strpos($_SERVER['HTTP_USER_AGENT'], 'iPad')){
									$type= 'ios';
								   }else if(strpos($_SERVER['HTTP_USER_AGENT'], 'Android')){
									$type='android';
								   }else{
									$type='other';
								   }
								loginlog($userinfo["phone"],$mechanism["name"],$mechanism["id"],$type);

								$token = $this->settoken();    //设置token值
								$ctime = strtotime("+7 days");   
								if(db("tokens")->where("id=".$userinfo["id"])->find()){
									$list = Db::name('tokens')->where('id',$userinfo["id"])->update([
										'token' => $token,
										'ctime' => $ctime
									 ]);
									 $userinfo["token"]=$token;
								}else{
									$s1["id"]=$userinfo["id"];
									$s1["token"]=$token;
									$s1["ctime"]=$ctime;
									db("tokens")->insertGetId($s1);
									$userinfo["token"]=$token;
								}
								
							

								return json(['status'=>200,'message'=>'登录成功','data'=>$userinfo]);
							}else{
								return json(['status'=>200,'message'=>'未选择身份','data'=>$userinfo]);
							}

					}else{

						file_put_contents("test.txt","走这里了".json_encode($userinfo).PHP_EOL,FILE_APPEND);
							return json(['status'=>200,'message'=>'未绑定','data'=>$userinfo]);
							
					}

					
				}else{
					file_put_contents("test.txt","结果openid".$openid.PHP_EOL,FILE_APPEND);
						if($openid!=""){
							$data["openid"]=$openid;
							$data["nickname"]=$arr["nickname"];
							$data["headimgurl"]=$arr["headimgurl"];
							$data["province"]=$arr["province"];
							$data["city"]=$arr["city"];
							$data["sex"]=$arr["sex"];

							$data["createtime"]= date('Y-m-d H:i:s',time());
							$data["mid"]=0;
							$userinfo["openid"]=$openid;
							$userinfo["nickname"]=$arr["nickname"];
							$userinfo["headimgurl"]=$arr["headimgurl"];
							
							$obj =db('users')->insertGetId($data);
							$userinfo["id"]=$obj;
							return json(['status'=>200,'message'=>'未绑定','data'=>$userinfo]);

						}
						
					

				}


				//file_put_contents("test.txt",$result.PHP_EOL,FILE_APPEND);
				//echo $result;
	}

	//绑定手机
	public function phonelogin(){
		$request = Request::instance();
	
		$openid =$request->post('openid');
		$phone =$request->post('phone');
		$code =$request->post('code');
		$nickname =$request->post('nickname');
		$headimgurl =$request->post('headimgurl');

		$smsloginfo = db("smslog")->where("code='".$code."'")->find();

		if($smsloginfo){

			$minute=floor((time()- strtotime($smsloginfo["createtime"])) %86400/60);
			if($minute<=5){
				$time = date('Y-m-d H:i:s',time());
				$obj = Db::execute('update users set phone=?,nickname=?,headimgurl=?,createtime=? where openid=?',[$phone,$nickname,$headimgurl,$time,$openid]);
				if($obj==true){
					return json(['status'=>200,'message'=>'绑定成功']);
				}else{
					return json(['status'=>400,'message'=>'绑定失败']);
				}
	
			}else{
				return json(['status'=>400,'message'=>'验证码超时了']);
			}
			

		}else{
			return json(['status'=>400,'message'=>'验证码不正确']);
			
		}

		


	}
	public function test(){
		//$str =  sendsms("13402943541","123","213","1");
		//$str =sendtempmsg("123","dd","123");
		//echo $str;
		//return "aaa";
	}


	private function request($url,$data=null){
		$curl=curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
 
        //设定为不验证证书和host
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
 
        if(!empty($data)){
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
 
        // 将curl_exec()获取的信息以文件流的形式返回，而不是直接输出
        curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
 
        $output=curl_exec($curl);
        if (false===$output) {
        	echo "<br/>",curl_error($curl),"<br/>";
        	return false;
        }
        curl_close($curl);
        return $output;
	}

	public function search(){
		$request = Request::instance();
		$name =$request->post('name');

		$mechanism =  db('mechanism')->where("number='".$name."'")->find();
		if($mechanism){

	

			$obj["status"]=200;
			$obj["message"]="查询成功";
			$obj["data"]=$mechanism;

			return json($obj);
		}else{
			$obj["status"]=500;
			$obj["message"]="无数据";
			return json($obj);
		}

	}
	//获取签到信息
	public function getsign(){
		$request = Request::instance();
		
		$userid  =$request->post('userid');
		$chooseclassid  =$request->post('classid');
		$classname  =$request->post('classname');

		$teacheranduser = db("teacheranduser")->where("userid=".$userid)->find();

		if($teacheranduser){
			$mid = $teacheranduser["mid"];
			$mycalss = Db::query('select * from myclass where mid='.$mid);
			$data["mycalss"]=$mycalss;
		

			if($chooseclassid){
				$classid = $chooseclassid;
				$oversign = db('sign')->where("classid=".$classid." and mid=".$mid." and to_days(signdate) = to_days(now())")->count();
				$sumcount =  db('student')->where("classid=".$classid." and mid=".$mid." and state=0")->count();
				$nosignresult =  Db::query('select count(*) as num from student where state=0 and  mid=? and classid=? and id not in(select studentid from sign where mid=? and classid=? and to_days(signdate) = to_days(now()))',[$mid,$classid,$mid,$classid]);
				$nosign = $nosignresult[0]["num"];
				$leavecount =  db('leave')->where("classid=".$classid." and to_days(stime) = to_days(now()) and mid=".$mid)->count();
			}else{
				$oversign = db('sign')->where("mid=".$mid." and to_days(signdate) = to_days(now())")->count();
				$sumcount =  db('student')->where("mid=".$mid." and state=0")->count();
				$nosignresult =  Db::query('select count(*) as num from student where state=0 and  mid=? and id not in(select studentid from sign where mid=? and to_days(signdate) = to_days(now()))',[$mid,$mid]);
				$nosign = $nosignresult[0]["num"];
				$leavecount =  db('leave')->where("mid=".$mid." and to_days(stime) = to_days(now())")->count();
			}
			$data["sumcount"]=$sumcount;
			$data["oversign"]=$oversign;
			$data["nosign"]=$nosign;
			$data["leavecount"]=$leavecount;

			$obj["status"]=200;
			$obj["data"]=$data;
			return json($obj);

		}else{

			$data["sumcount"]=0;
			$data["oversign"]=0;
			$data["nosign"]=0;
			$data["leavecount"]=0;
			$obj["status"]=400;
			$obj["message"]="未绑定班级";
			return json($obj);
		}

	}
	//获取老师签到信息列表
	public function getsignlist(){

		$request = Request::instance();

		$userid = $request->post('userid');
		$studentid = $request->post('studentid');
		$index = $request->post('index');

		
		$user = db("users")->where("id=".$userid)->find();
		$list = array();
		if($index==1){
			//签到消息
			if($user["type"]=="1"){
				$where="studentid=".$studentid."";
			}else if($user["type"]=="2"){
				$where="teacherid=".$userid."";
			}
			if($where!=""){
				$list = db('sign')->where($where)->select();
				foreach ($list as $key => &$value) {
					$student = db("student")->where("id=".$value["studentid"])->find();
					$value["truename"]=$student["truename"];
						
				}

			}
		
		}else if($index==0){
			//系统消息
			$list = db("messagelist")->where("userid=".$studentid)->select();
			foreach ($list as $key => &$value) {
				$message = db("message")->where("id=".$value["msgid"])->find();
				$value["title"]=$message["title"];
			}

		}
	
	
		$obj["data"]=$list;
		$obj["status"]=200;


		return json($obj);
	}
	//获取家长签到记录
	public function getstudentsignlist(){
		$request = Request::instance();

		$studentid = $request->post('studentid');
		$page = $request->post('page');
		$size = 10;

		$where="studentid=".$studentid;
		$count =db('sign')->where($where)->count();
		$first = $size * ($page -1);
			
		$list = db('sign')->where($where)->limit($first,$size)->select();
		$url =  $_SERVER["REQUEST_SCHEME"].'://'.$_SERVER["SERVER_NAME"].'/static/uploads/';
		foreach ($list as $key => &$value) {
			$student = db("student")->where("id=".$value["studentid"])->find();
			$value["truename"]=$student["truename"];
				
		}
		$obj["count"]=(int)($count/$size)+1;
		$obj["allcount"]=$count;
		$obj["data"]=$list;
		$obj["status"]=200;


		return json($obj);


	}
	//打卡
    public function sign()
    {
       $request = Request::instance();
		
		$number =$request->post('number');


		$data["type"] =$request->post('type');
		$data["mid"] =$request->post('mid');
		$userid = $request->post('userid');
		$classid = $request->post('classid');
		
		$teacheranduser= db("teacheranduser")->where("userid=".$userid)->find();

		$data["teacherid"] =$teacheranduser["teacherid"];
		$data["signdate"] = date("Y-m-d H:i:s");
		$data["createtime"] = date("Y-m-d");
	
	
		$student_card = db('student_card')->where("mid=".$data["mid"]." and cardnumber='".$number."'")->find();
		if(!$student_card){
			return json(['status'=>500,'message'=>'卡号不存在']);
		}

		$studentid = $student_card["studentid"];
		$student= db("student")->where("id=".$studentid)->find();

	
		$sys_webconfig= db("sys_webconfig")->where("mid=".$data["mid"])->find();

		$signnum = 1;
		$signjgtime=60;
		if($sys_webconfig){
			$signnum= $sys_webconfig["signnum"];
			$signjgtime= $sys_webconfig["signjgtime"] * 60;
		}

		if($student){
			$myclass = db('myclass')->where("id=".$student["classid"])->find();


			$signinfo = db('sign')->where("studentid=".$student["id"]." and to_days(signdate) = to_days(now())")->order("id desc")->select();


			if($signnum>count($signinfo)){

				if(count($signinfo)!=0){
					 $enddate = date("Y-m-d H:i:s");
					 $startdate=$signinfo[0]["signdate"];
					$fenzhong=floor((strtotime($enddate)-strtotime($startdate))%86400/60);
					file_put_contents("test.txt","当前时间".$enddate."上一次签到时间".$startdate."时间差".$fenzhong."分钟".PHP_EOL,FILE_APPEND);
					if($fenzhong<$signjgtime){
						return json(['status'=>500,'message'=>'距离上一次打卡时间过短']);
					}
				}
				

				$data["studentid"]=$student["id"];
				$data["classid"]=$student["classid"];
				$obj = db('sign')->insertGetId($data);
				if($obj){
					//推送
					$now= date("Y-m-d H:i:s");
					//用户充值了，并且没有过期
					if(strtotime($student["videoetime"])>strtotime($now)){
					
						$studentandparent = db("studentandparent")->where("studentid=".$student["id"])->find();
						if($studentandparent){
							$parent = db("users")->where("id=".$studentandparent["userid"])->find();
							if($parent&&$parent["openid"]!=""){
								$arr[0]=$student["truename"];
								$arr[1]=$myclass["classname"];
								$arr[2]=$data["signdate"];
	
								sendtempmsg("sX-_cer_h2m6fyoImTL-PFhzB64JM8hWKGb6iz8ahfo",$parent["openid"],$student["truename"]."签到成功！",$arr);
							}
						}
					}

					
				
					return json(['status'=>200,'message'=>'签到成功','data'=>$student]);
				}else{
					return json(['status'=>500,'message'=>'系统异常']);
				}
			}else{

				return json(['status'=>500,'message'=>'请勿重复签到']);
				
			}
			
			
		}else{
			return json(['status'=>500,'message'=>'学生信息不存在']);

		}
	}
	public function searchstudent(){
		$request = Request::instance();
		$number =$request->post('number');
		$data["mid"] =$request->post('mid');


		$student_card = db('student_card')->where("mid=".$data["mid"]." and cardnumber='".$number."'")->find();
		if(!$student_card){
			return json(['status'=>500,'message'=>'卡不存在']);
		}

		$studentid = $student_card["studentid"];
		$student= db("student")->where("id=".$studentid." and state=0")->find();

	
		if($student){
			$classinfo = db('myclass')->where("id=".$student["classid"])->find();
			if($classinfo["teacherid"]){
				$teacherinfo = db('teacher')->where("id=".$classinfo["teacherid"])->find();
				if($teacherinfo){
					$student["teachername"]=$teacherinfo["teachername"];
				}else{
					$student["teachername"]="";
				}
			}
		
			$student["classname"]=$classinfo["classname"];
		
		
			if($student["imgurl"]!=""){
				$url =  $_SERVER["REQUEST_SCHEME"].'://'.$_SERVER["SERVER_NAME"].'/static/uploads/';
				$student["imgurl"]= $url.$student["imgurl"];
			}



			return json(['status'=>200,'message'=>'','data'=>$student]);
		}else{
			return json(['status'=>500,'message'=>'学号不存在']);
		}
	}
	public function myinfo(){
		$request = Request::instance();
		$openid =$request->post('openid');
		$where="openid='".$openid."'";

		$sytemconfig = db("sys_webconfig")->where("mid=0")->find();

		$userinfo = db('users')->where($where)->find();
		if($userinfo){
			$mechanism = db('mechanism')->where("id=".$userinfo["mid"])->find();
		
			//家长
			if($userinfo["type"]=="1"){
				$studentandparent = db('studentandparent')->where("userid=".$userinfo["id"])->order("seq asc")->find();
				if($studentandparent){
					$student = db('student')->where("id=".$studentandparent["studentid"])->find();
					if($student){
						$myclass= db('myclass')->where("id=".$student["classid"])->find();
						if($myclass){
		
							$student["classname"]=$myclass["classname"];
						}
					}
					
					if($student["videoetime"]==""||$student["videoetime"]=="null"){
						$endtime="已到期";
					}else{

						$endtime = date("Y-m-d",strtotime($student["videoetime"])); 
					}
				
				
					
					$student["endtime"]=$endtime;
					$student["kefuphone"]= $sytemconfig["kefuphone"];

					if($student["imgurl"]==""){
						$student["headimgurl"]= $_SERVER["REQUEST_SCHEME"].'://'.$_SERVER["SERVER_NAME"].'/static/images/headimg.png';
					}else{
						$student["headimgurl"]= $_SERVER["REQUEST_SCHEME"].'://'.$_SERVER["SERVER_NAME"]."/static/uploads/".$student["imgurl"];
					}
	
					$obj["status"]=200;
					$obj["data"]=$student;
					return json($obj);
				}
			//老师	
			}else  if($userinfo["type"]=="2"){
				$endtime = date("Y-m-d",strtotime($mechanism["endtime"])); 
				$teacheranduser = db('teacheranduser')->where("userid=".$userinfo["id"])->find();
				$teacher = db("teacher")->where("id=".$teacheranduser["teacherid"])->find();
				$data["endtime"]=$endtime;
				$data["kefuphone"]= $sytemconfig["kefuphone"];
				$data["truename"]= $teacher["teachername"];
				$data["headimgurl"]=$userinfo["headimgurl"];

				$obj["status"]=200;
				$obj["data"]=$data;
				return json($obj);
			}
			
		}else{
		
				return json(['status'=>500,'message'=>'系统异常']);
		
		}
	}
	public function getfood(){
		$request = Request::instance();

		$mid = $request->post('mid');
		$page = $request->post('page');
		$size = 10;

		$where="mid=".$mid;
		$count =  db("food")->where($where)->Distinct(true)->field('mydate')->order('mydate desc')->limit($first,$size)->count(); 
		$first = $size * ($page -1);
	
		$url =  $_SERVER["REQUEST_SCHEME"].'://'.$_SERVER["SERVER_NAME"].'/static/uploads/';

		$sys_pic = db("sys_pic")->where("typeid=2 and state=1")->order("id desc")->find();
		$defaulturl = $url.$sys_pic["imgurl"];

		$list = db("food")->where($where)->Distinct(true)->field('mydate')->order('mydate desc')->limit($first,$size)->select(); 
		foreach ($list as $key => &$value) {
			$mydate =  $value["mydate"];
			$itemlist =  db("food")->where("mydate='".$mydate."'")->select();
			foreach ($itemlist as $key1 => &$value1) {
				if($value1["imgurl"]!=""){
					$value1["imgurl"]= $url.$value1["imgurl"];
				}else{
					$value1["imgurl"]= $defaulturl;
				}
				$result = Db::query('select avg(star) as star from foodstar where foodid=?',[$value1["id"]]);
				$value1["star"]=$result[0]["star"];
			}
			$value["list"]=$itemlist;
			$value["mydate"]=date("Y-m-d",strtotime($value["mydate"])); 
				
		}
		$obj["count"]=(int)($count/$size)+1;
		$obj["allcount"]=$count;
		$obj["data"]=$list;
		$obj["status"]=200;


		return json($obj);

		
	}
	public function foodadd(){
		$request = Request::instance();

		$data["title"] = $request->post('title');
		$data["imgurl"] = $request->post('image');
		$url =  $_SERVER["REQUEST_SCHEME"].'://'.$_SERVER["SERVER_NAME"].'/static/uploads/';
		$data["imgurl"]=str_replace($url,"",$data["imgurl"]);
		$data["desc"] = $request->post('desc');
		$data["type"] = $request->post('type');
		$data["mid"] = $request->post('mid');
		$data["createtime"] = date("Y-m-d H:i:sa");
		$data["mydate"] = $request->post('date');
	

		$result = db('food')->insertGetId($data);
		
		$obj["message"]="添加成功";
		$obj["status"]=200;


		return json($obj);

		
	}
	public function getfoodinfo(){
		$request = Request::instance();
		$id = $request->post('id');
		$userid = $request->post('userid');
		$where="id=".$id;
		$list = db('food')->where($where)->find();
		$url =  $_SERVER["REQUEST_SCHEME"].'://'.$_SERVER["SERVER_NAME"].'/static/uploads/';
		$sys_pic = db("sys_pic")->where("typeid=2 and state=1")->order("id desc")->find();
		$defaulturl = $url.$sys_pic["imgurl"];

		if($list["imgurl"]!=""){
			$list["imgurl"]= $url.$list["imgurl"];
		}else{
			$list["imgurl"]= $defaulturl;
		}
		$result = Db::query('select avg(star) as star from foodstar where foodid=?',[$id]);
		$list["star"]=$result[0]["star"];

		$foodstar = db("foodstar")->where("userid=".$userid." and foodid=".$id)->find();
		if($foodstar){
			$list["mystar"]=$foodstar["star"];
		}else{
			$list["mystar"]="您还没有评分";
		}
		


		$obj["data"]=$list;
		$obj["status"]=200;
		return json($obj);	
	}
	public function foodstar(){
		$request = Request::instance();
		$foodid = $request->post('foodid');
		$userid = $request->post('userid');
		$star = $request->post('star');

		$foodstar = db("foodstar")->where("userid=".$userid." and foodid=".$foodid)->find();
		if($foodstar){
			$updateresult = Db::execute('update foodstar set star=?,createtime=? where userid=? and foodid=?',[$star, date("Y-m-d H:i:sa"),$userid,$foodid]);
		}else{
			$data["foodid"]=$foodid;
			$data["userid"]=$userid;
			$data["star"]=$star;
			$data["createtime"]= date("Y-m-d H:i:sa");
			db("foodstar")->insertGetId($data);
		}
		
		$result = Db::query('select avg(star) as star from foodstar where foodid=?',[$foodid]);
	
		
		$obj["status"]=200;
		$obj["data"]=$result[0]["star"];
		return json($obj);	
	}

	public function getnewsinfo(){
		$request = Request::instance();
		$id = $request->post('id');
		$where="id=".$id;
		$list = db('news')->where($where)->find();
		if($list["imgurl"]!=""){
			$url =  $_SERVER["REQUEST_SCHEME"].'://'.$_SERVER["SERVER_NAME"].'/static/uploads/';
			$list["imgurl"]=$url.$list["imgurl"];
		}
	
		$obj["data"]=$list;
		$obj["status"]=200;
		return json($obj);	
	}
	public function getworkinfo(){
		$request = Request::instance();
		$id = $request->post('id');
		$studentid = $request->post('studentid');
		$teacherid = $request->post('teacherid');



		
		$where="id=".$id;
		$list = db('work')->where($where)->find();
		$url =  $_SERVER["REQUEST_SCHEME"].'://'.$_SERVER["SERVER_NAME"].'/static/uploads/';
		if($list["imgurl"]!=""){

			$list["imgurl"]=$url.$list["imgurl"];
		}
		$teacher = db("teacher")->where("id=".$list["teacherid"])->find();
		if($teacher){
			$list["teachername"]=$teacher["teachername"];
		}

		$list["overtime"]=date("Y-m-d",strtotime($list["overtime"])); 

		if($studentid!=""&&$studentid!="undefined"){
			$list["workresultstate"]="1";
			$workresult=db("workresult")->where("workid=".$list["id"]." and studentid=".$studentid)->order("id desc")->select();
			if(count($workresult)==0){
				$list["workresultstate"]="0";
			}else{
				foreach ($workresult as $key => &$value) {

					$value["imglist"]= explode(",", $value["imglist"]);
				}
				$list["workresult"]=$workresult;
			}
		

		}else if($teacherid!=""&&$teacherid!="undefined"){
			$list["workresultstate"]="2";
			$workresult=db("workresult")->where("workid=".$list["id"])->order("id desc")->select();
			if(count($workresult)==0){
				$list["workresultstate"]="0";
			}else{
				foreach ($workresult as $key => &$value) {
					$student = db("student")->where("id=".$value["studentid"])->find();
					$value["studentname"]=$student["truename"];
					$value["imglist"]= explode(",", $value["imglist"]);
				}
				$list["workresult"]=$workresult;
			}
		
		}
		
		
		
		
		
	
		$obj["data"]=$list;
		$obj["status"]=200;
		return json($obj);	
	}
	//风采
	public function getnews(){
		$request = Request::instance();

		$mid = $request->post('mid');
		$page = $request->post('page');
		$size = 10;

		$where="mid=".$mid;
		$count =db('news')->where($where)->count();
		$first = $size * ($page -1);
	
	
		$list = db('news')->where($where)->order("id desc")->limit($first,$size)->select();
		$url =  $_SERVER["REQUEST_SCHEME"].'://'.$_SERVER["SERVER_NAME"].'/static/uploads/';
		foreach ($list as $key => &$value) {
			

			if($value["imgurl"]!=""){

				$value["imgurl"]=$url.$value["imgurl"];
			}
			$value["createtime"]=date("Y-m-d",strtotime($value["createtime"])); 
				
		}
		$obj["count"]=(int)($count/$size)+1;
		$obj["allcount"]=$count;
		$obj["data"]=$list;
		$obj["status"]=200;


		return json($obj);

		
	}
	//请假
	function leaveadd(){
		
		$request = Request::instance();	
	
		
		$student = db("student")->where("id=".$request->post("sid"))->find();
		$mycalss = db("myclass")->where("id=".$student["classid"])->find();

		$data["userid"] =$request->post('userid');
		$data["classid"] =$mycalss["id"];
		$data["sid"] =$request->post('sid');
		$data["stime"] =$request->post('stime');
		$data["etime"] =$request->post('etime');
		$data["day"] =$request->post('day');
		$data["desc"] =$request->post('desc');
		$data["state"] = 0;
		$data["teacherid"] =$mycalss["teacherid"];
		$data["createtime"] = date('Y-m-d H:i:s',time());
		$data["mid"] = $student["mid"];
	
		if(db('leave')->insertGetId($data)){
			 return json(['status'=>200,'message'=>'提交成功']);
			
		}else{
			return json(['status'=>500,'message'=>'提交失败']);
		}
			
	}
	//请假审核
	public function leavesh(){
		$request = Request::instance();	
		$state = $request->post("state");
		$userid = $request->post("userid");
		$desc = $request->post("desc");
		$id = $request->post("id");
		$user = db("users")->where("id=".$userid)->find();
		$teacheranduser = db("teacheranduser")->where("userid=".$userid)->find();
		$teacherid = $teacheranduser["teacherid"];
		
		$shtime =date('Y-m-d H:i:s',time());

		$updateresult = Db::execute('update `leave` set state=?,teacherid=?,result=?,shtime=? where id=?',[$state,$teacherid,$desc,$shtime,$id]);
		
		if($updateresult){
			return json(['status'=>200,'message'=>'审核成功']);
		   
	   }else{
		   return json(['status'=>500,'message'=>'审核失败']);
	   }
	}
	 public function getleavea(){
		$request = Request::instance();	
		$studentid = $request->post("studentid");
		$teacherid = $request->post("teacherid");
		$usertype = $request->post("usertype");


		$size =10;
		$page = $request->post('page');

		if($usertype=="1"){
			$countresult = Db::query('select count(*) as num  from `leave` where sid=?',[$studentid]);
			$count =$countresult[0]["num"];
			$first = $size * ($page -1);
			$list = Db::query('select * from `leave` where sid=? order by id desc limit ?,?',[$studentid,$first,$size]);
			foreach ($list as $key => &$value) {
				$userid = $value["userid"];
				$sid = $value["sid"];
				$user = db("users")->where("id=".$userid)->find();
				$value["truename"]=$user["truename"];
				$student = db("student")->where("id=".$sid)->find();
				$value["studentname"]=$student["truename"];

				$value["stime"]=date("Y-m-d",strtotime($value["stime"])); 
				$value["etime"]=date("Y-m-d",strtotime($value["etime"])); 
				

			}

			$obj["count"]=(int)($count/$size)+1;
			$obj["allcount"]=$count;
			$obj["data"]=$list;
			$obj["status"]=200;
			return json($obj);

		}else if($usertype=="2"){
		
			
			$countresult = Db::query('select count(*) as num  from `leave` where classid in (select classid from teacherandclass where teacherid=?)',[$teacherid]);
	
			$count =$countresult[0]["num"];
			$first = $size * ($page -1);
			$list = Db::query('select * from `leave` where classid in (select classid from teacherandclass where teacherid=?)  order by `leave`.id desc limit ?,?',[$teacherid,$first,$size]);
			foreach ($list as $key => &$value) {
				$userid = $value["userid"];
				$sid = $value["sid"];
				$user = db("users")->where("id=".$userid)->find();
				$value["truename"]=$user["truename"];
				$student = db("student")->where("id=".$sid)->find();
				$value["studentname"]=$student["truename"];

				$value["stime"]=date("Y-m-d",strtotime($value["stime"])); 
				$value["etime"]=date("Y-m-d",strtotime($value["etime"])); 

			}

			$obj["count"]=(int)($count/$size)+1;
			$obj["allcount"]=$count;
			$obj["data"]=$list;
			$obj["status"]=200;
			return json($obj);
		}

	
		
	}
	
	function leavedel(){
		$request = Request::instance();
		$id =$request->post('id');
		
			$where = 'id='.$id;
		  
		   $list=db('leave')->where($where)->delete();
		   if($list!==false) {
			 return ['status'=>200,'message'=>'删除成功'];
		   }else{
			  return ['status'=>500,'message'=>'删除失败'];
		   }
		
	}
	
		//视频
	public function getvideo(){
		$request = Request::instance();

		$mid = $request->post('mid');
		$page = $request->post('page');
		$size = 10;

		$studentid = $_POST["studentid"];
		$teacherid = $_POST["teacherid"];
		$now= date("Y-m-d H:i:s");
		//用户充值了，并且没有过期
		$url =  $_SERVER["REQUEST_SCHEME"].'://'.$_SERVER["SERVER_NAME"].'/static/uploads/';
		if($teacherid!=""){
			$teacher = db("teacher")->where("id=".$teacherid)->find();
			if($teacher["isyuanzhang"]=="1"){
				$countresult = Db::query("select count(*) as num  from video where mid=".$mid);
				$first = $size * ($page -1);
				$list = Db::query("select * from video where mid=".$mid." limit ".$first.",".$size);
			}else{
				$countresult = Db::query("select count(*) as num  from video where classid in(select classid from teacherandclass where teacherandclass.teacherid=".$teacherid.")");
				$first = $size * ($page -1);
				$list = Db::query("select * from video where classid in(select classid from teacherandclass where teacherandclass.teacherid=".$teacherid.") limit ".$first.
				" ,".$size);
			}
				foreach ($list as $key => &$value) {
					if($value["onlinenum"]==""){
						$value["onlinenum"]=0;
					}
					if($value["imgurl"]!=""){
						$value["imgurl"]= $url.$value["imgurl"];
					}

					$onlinenum= db("useronline")->where("videoid=".$value["id"]." and  onlinetime>DATE_SUB(NOW(),INTERVAL  10 SECOND)")->count();
					$value["onlinenum"]=$onlinenum;
				}
				$count = $countresult[0]["num"];
				$obj["count"]=(int)($count/$size)+1;
				$obj["allcount"]=$count;
				$obj["data"]=$list;
				$obj["status"]=200;
				return json($obj);
				
			

		}else{
			$student  = db("student")->where("id=".$studentid)->find();
			if(strtotime($student["videoetime"])>strtotime($now)&&$student["modeltype"]=="2"){
	
				$classid = $student["classid"];
	
				$where="mid=".$mid." and classid=".$classid;
				$count =db('video')->where($where)->count();
				$first = $size * ($page -1);
					
				$list = db('video')->where($where)->limit($first,$size)->select();
			
		
				
				foreach ($list as $key => &$value) {
					if($value["onlinenum"]==""){
						$value["onlinenum"]=0;
					}
					if($value["imgurl"]!=""){
						$value["imgurl"]= $url.$value["imgurl"];
					}
					$onlinenum= db("useronline")->where("videoid=".$value["id"]." and  onlinetime>DATE_SUB(NOW(),INTERVAL  10 SECOND)")->count();
					$value["onlinenum"]=$onlinenum;
				
						
				}
				
				$obj["count"]=(int)($count/$size)+1;
				$obj["allcount"]=$count;
				$obj["data"]=$list;
				$obj["status"]=200;
				return json($obj);
		
			}else{
				$obj["count"]=0;
				$obj["allcount"]=0;
				$obj["data"]=[];
				$obj["status"]=200;
				return json($obj);
			}

		}

		

	

		

	

	}
	public function getvideoinfo(){
		$request = Request::instance();
		$id = $request->post('id');
		$studentid = $request->post('studentid');
		$teacherid = $request->post('teacherid');
		$usertype = $request->post('usertype');


		if($usertype=="1"){
			$student = db("student")->where("id=".$studentid)->find();
			if($student){
				if($student["videoetime"]==""){
					return json(['status'=>500,'message'=>'没有权限，请联系机构客服']);

				}else{
					$videoetime=strtotime($student["videoetime"]);
					if($videoetime<time()){
						return json(['status'=>500,'message'=>'没有权限，请联系机构客服']);
					}
				}
			}
		}
		
	
		$where="id=".$id;
		$list = db('video')->where($where)->find();
		$mid = $list["mid"];
		$mechanism = db("mechanism")->where("id=".$mid)->find();
		if($list["videourl"]!=""){
			$sys_webconfig = db("sys_webconfig")->where("mid=0")->find();
		
		
			$time = date("Y-m-d H:i:s",time()+7200);
			$play = getplayurl2($sys_webconfig["cdn"], $list["videourl"], $sys_webconfig["playapikey"], $time);
			$list["rtmpurl"]=$play[0];
		
		}

		$obj["data"]=$list;
		$obj["status"]=200;
		return json($obj);	
	}
	//消息
	public function getmessage(){
		$request = Request::instance();

		$mid = $request->post('mid');
		$where="mid=".$mid;
		$count =db('message')->where($where)->count();
		$first = $_GET["size"] * ($_GET["page"] -1);
		 
		$list = db('message')->where("")->order("id desc")->limit($first,$_GET["size"])->select();
		foreach ($list as $key => &$value) {
			
			
			
		}
		$obj["count"]=(int)($count/$_GET["size"])+1;
		$obj["allcount"]=$count;
		$obj["list"]=$list;
		return json($obj);


	}
	public function getmessageinfo(){
		$request = Request::instance();
		$id = $request->post('id');
		$list = db('message')->where("id=".$id)->find();


		$obj["data"]=$list;
		$obj["status"]=200;
		return json($obj);
	}
	//添加作业
	public function workadd(){
		$request = Request::instance();

		$userid = $request->post('userid');
		$user = db("users")->where("id=".$userid)->find();
		$teacheranduser = db("teacheranduser")->where("userid=".$userid)->find();

		$data["title"] = $request->post('title');
		$data["desc"] = $request->post('desc');
		$data["teacherid"] = $teacheranduser["teacherid"];
		$data["createtime"] = date('Y-m-d H:i:s',time());
		$data["overtime"] = $request->post('overtime');
		$data["classid"] = $request->post('classid');
		$data["mid"] = $user["mid"];
		$data["imgurl"] = $request->post('imglist');
		$url =  $_SERVER["REQUEST_SCHEME"].'://'.$_SERVER["SERVER_NAME"].'/static/uploads/';
		$data["imgurl"]=str_replace($url,"",$data["imgurl"]);

		if(db('work')->insertGetId($data)){

			return json(['status'=>200,'message'=>'添加成功']);
		}else{
			return json(['status'=>500,'message'=>'添加失败']);
		}


	}
	//作业
	public function getwork(){
		$request = Request::instance();

		$studentid = $request->post('studentid');
		$teacherid = $request->post('teacherid');

		if($studentid!=""&&$studentid!="undefined"){
			$student = db("student")->where("id=".$studentid)->find();
			$where="classid=".$student["classid"];
		}else if($teacherid!=""&&$teacherid!="undefined"){
			$where="teacherid=".$teacherid;
		}

		$page = $request->post('page');
		$size = 10;

	
		$count =db('work')->where($where)->count();
		$first = $size * ($page -1);
			
		$list = db('work')->where($where)->order("id desc")->limit($first,$size)->select();
		$url =  $_SERVER["REQUEST_SCHEME"].'://'.$_SERVER["SERVER_NAME"].'/static/uploads/';
		foreach ($list as $key => &$value) {
			
				//$teacherinfo  =db('teacher')->where("id=".$value["teacherid"])->find();
				//$value["teachername"]=$teacherinfo["teachername"];
				if($value["imgurl"]!=""){

					$value["imgurl"]=$url.$value["imgurl"];
				}
			
				$classinfo  =db('myclass')->where("id=".$value["classid"])->find();
				$value["classname"]=$classinfo["classname"];
				$value["overtime"]=date("Y-m-d",strtotime($value["overtime"])); 
		}
		$obj["count"]=(int)($count/$size)+1;
		$obj["allcount"]=$count;
		$obj["data"]=$list;
		$obj["status"]=200;
		return json($obj);
	}
	//获取学生信息
	public function getstudent(){
		$request = Request::instance();

		$studentid = $request->post('studentid');
		$student = db('student')->where("id=".$studentid)->find();
		$myclass = db('myclass')->where("id=".$student["classid"])->find();
		if($myclass["teacherid"]){
			$teacher = db('teacher')->where("id=".$myclass["teacherid"])->find();
			if($teacher){
				$student["teachername"]= $teacher["teachername"];
				$student["teacherphone"]= $teacher["phone"];
			}
		}
		

		if($myclass){
			$student["classname"]= $myclass["classname"];
		}
	

		$url =  $_SERVER["REQUEST_SCHEME"].'://'.$_SERVER["SERVER_NAME"].'/static/uploads/';
		if($student["imgurl"]!=""){

			$student["imgurl"]=$url.$student["imgurl"];
		}

		$obj["status"]=200;
		$obj["data"]=$student;
		return json($obj);

	}
	//获取教师信息
	public function getteacher(){
		$request = Request::instance();

		$userid = $request->post('userid');
		$user = db("users")->where("id=".$userid)->find();
		$teacheranduser = db("teacheranduser")->where("userid=".$userid)->find();
		if($teacheranduser){
				$teacher= db("teacher")->where("id=".$teacheranduser["teacherid"])->find();
				$user["teachername"]= $teacher["teachername"];
				$user["phone"]= $teacher["phone"];
				$user["sex"]= $teacher["sex"];
			
		}
		

	
		

		$obj["status"]=200;
		$obj["data"]=$user;
		return json($obj);

	}
	//获取班级信息
	public function getclass(){
		$request = Request::instance();

		$mid = $request->post('mid');
		$myclass = db("myclass")->where("mid=".$mid)->select();
		$obj["status"]=200;
		$obj["data"]=$myclass;
		return json($obj);
	}
	//机构申请
	public function mechanismsq(){
		$request = Request::instance();

		$appid=Config::get('appid');
		$secret=Config::get('secret');

		if($request->isPost()){
			$openid =$request->post('openid');
			$code= $request->post('code');
			$smsloginfo = db("smslog")->where("code='".$code."'")->find();

			if($smsloginfo){
	
				$minute=floor((time()- strtotime($smsloginfo["createtime"])) %86400/60);
				if($minute<=5){
					$addresscode= $request->post('addresscode');
					$address= $request->post('address');
					$items = explode("-",$address);

					$mechanism =db('mechanism')->where("province='".$items[0]."' and city='".$items[1]."' and area='".$items[2]."'")->order("id desc")->find();
					if($mechanism){
					$number = $mechanism["number"]+1;
					$data["number"]=$number;
					}else{
						$data["number"]= $addresscode."1";
					}



					$data["name"]= $request->post('name');
					$data["truename"]= $request->post('truename');
					$data["phone"]= $request->post('phone');
					$data["createtime"]= date('Y-m-d H:i:s',time());
					$data["province"]= $items[0];
					$data["city"]=  $items[1];
					$data["area"]=  $items[2];
					
					
					$data["desc"]= $request->post('desc');
					$data["state"]= "0";
					$data["openid"]= $openid;

					$mechanism = db("mechanism")->where("name='".$data["name"]."'")->find();
					$mechanism2 = db("mechanism")->where("phone='".$data["phone"]."'")->find();
					if($mechanism){
						return json(['status'=>500,'message'=>'机构名称重复了']);
					}else if($mechanism2){
						return json(['status'=>500,'message'=>'联系方式重复了']);

					}else{
						if(db('mechanism')->insertGetId($data)){
							//给用户发短信
						
							$smsarr[0]=$data["truename"];
							$smsarr[1]=$data["createtime"];
							$smsarr[2]=$data["name"];
							sendsms($data["phone"],"","SMS_157065883","1",$smsarr);
							//给用户推送
							
							$items = [];
							$items[0]=$data["truename"];
							$items[1]=$data["createtime"];
							$items[2]=$data["name"];
							$items[3]=$data["phone"];

							sendtempmsg4("PqX0Q3JivhsZfXysR-jeSD1RH6TCC--dQ_b5Q-uokaw",$openid,"您的机构加入申请等待审核，请耐心等待",$items);
						
							//给客服推送
							$kefulist = db("users")->where("iskefu=1")->select();
							foreach ($kefulist as $key => &$value) {
					
								$arr=array($data["name"],$data["phone"],$data["province"]."-".$data["city"]."-".$data["area"],"",$data["createtime"]);
			

								sendtempmsg2("emuX9hrhhWy2HJgFEiKW86_sVdU1w6vdKSBGOkI_118",$value["openid"],"",$arr);
							}
						


							return json(['status'=>200,'message'=>'申请成功']);
							
						}else{
							return json(['status'=>500,'message'=>'申请失败']);
						}
					}
		
				}else{
					return json(['status'=>400,'message'=>'验证码超时了']);
				}
				
	
			}else{
				return json(['status'=>400,'message'=>'验证码不正确']);
				
			}
		}else{
			if(!$_GET["code"]){
				$url= "http://jiao.wulinkyun.com/wx/index/mechanismsq";
				$url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=".$url."&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
				//发送GET请求
				header("Location: ".$url);
				exit();//必要
			}else{
				$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=".$_GET["code"]."&grant_type=authorization_code";
            	$result=$this->request($url);
				if (!$result) {
					return false;
				}
			
			
				$arr=json_decode($result,true);		
				$openid=$arr['openid'];
				$this->assign('openid',$openid);
				return view();
			 }

		}


	}
	

	public function wxquanxian()
	{	
		$request = Request::instance();
		$url = $request->post('url');
 		file_put_contents("test.txt",$url.PHP_EOL,FILE_APPEND);
		$jssdkObj = new Jssdk(Config::get('appid'), Config::get('secret'));
        $res = $jssdkObj->getSignPackage($url);
        $appId = $res['appId'];
        $timestamp = $res['timestamp'];
        $nonceStr = $res['nonceStr'];
		$signature = $res['signature'];
		

		$obj = array(
			'appId'=>$appId,
			'timestamp'=>$timestamp,
			'nonceStr'=>$nonceStr,
			'signature'=>$signature
		);

	file_put_contents("test.txt","cc".json_encode($obj),FILE_APPEND);
		return json($obj);
		
 
	
	}
	public static function settoken()    //设置token值的方法
    {
        $str = md5(uniqid(md5(microtime(true)),true));
        $str = sha1($str);
        return $str;
    }


    public static function checktokens($token)   //检查token值的方法
    {
        $list = Db::name('tokens')->field('ctime')->where('token="'.$token.'"')->find();
        if(!empty($list)){
            if(time()-$list['ctime'] > 0){     //长时间未操作让用户重新登录
                return 1;
            }
            $ntime = strtotime("+7 days");   //检查无误延长操作时间
            $up = Db::name('tokens')->where('token',$token)->update([
                    'ctime' => $ntime
                ]);
            if($up){
                return 0;
            }
        }
        return 2;
    }
	public function uploadheadimg(){
		$request = Request::instance();
		$base64 = $request->post('data');
		$studentid=  $request->post('studentid');


		//file_put_contents("test.txt","studentid".$studentid."data".$base64.PHP_EOL,FILE_APPEND);

		$path = ROOT_PATH . 'public' . DS . 'static'. DS .'uploads/headimg/';
		if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64, $result)){
				$type = $result[2];
				$filename = "headimg/".time().".{$type}";
			    $new_file = $path.time().".{$type}";
		  if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64)))){
				if($studentid){
					$updateresult = Db::execute('update student set imgurl=? where id=?',[$filename,$studentid]);
				}
				return "success";
		  }else{
			return "error2";
		  }
		}else{
			return "error";
		}
		
	}
	public function uploadimg(){
		$request = Request::instance();

		$jssdkObj = new Jssdk(Config::get('appid'), Config::get('secret'));
		$accesstoken = $jssdkObj->getAccessToken();
		$serverId =  $request->post('serverId');
		$filename = date('Ymd').DS.date('YmdHis').'.jpg';
		$path = ROOT_PATH . 'public' . DS . 'static'. DS .'uploads/'.$filename;
		$dir = ROOT_PATH . 'public' . DS . 'static'. DS .'uploads/'.date('Ymd').DS;
		if (!file_exists($dir)){
            mkdir ($dir,0777,true);
        } else {
          
		}
		

		$url ="http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=".$accesstoken."&media_id=".$serverId;
	
		$img = httppost($url);
		file_put_contents($path,$img);
	//	file_put_contents("test.txt","filename".$filename.PHP_EOL,FILE_APPEND);
		$url =  $_SERVER["REQUEST_SCHEME"].'://'.$_SERVER["SERVER_NAME"].'/static/uploads/';
		return $url.$filename;



	}
	public function workresultadd(){
		$request = Request::instance();
		$data["studentid"] = $request->post('studentid');
		$data["userid"] = $request->post('userid');
		$data["desc"] = $request->post('desc');
		$data["imglist"] = $request->post('imglist');
		$data["createtime"] =  date('Y-m-d H:i:s',time());
		$data["workid"] = $request->post('workid');
		$data["state"] = "1";
		$data["mid"] =  $request->post('mid');

		if(db('workresult')->insertGetId($data)){
			return json(['status'=>200,'message'=>'提交成功']);
		   
	   }else{
		   return json(['status'=>500,'message'=>'提交失败']);
	   }
	}
	//签到统计
	public function signtj(){
		$classid = $_POST["classid"];
		$type =$_POST["type"];
		$mid =$_POST["mid"];

		//$oversign = db('sign')->where("classid=".$classid." and mid=".$mid." and to_days(signdate) = to_days(now())")->count();
		//$sumcount =  db('student')->where("classid=".$classid." and mid=".$mid." and state=0")->count();
		//$nosign = $sumcount- $oversign;
		//$leavecount =  db('leave')->where("classid=".$classid." and to_days(stime) = to_days(now()) and mid=".$mid)->count();

		if($type=="1"){
			$where="student.mid=".$mid." and state=0";
			if($classid!=""){
				$where=$where." and student.classid=".$classid;
			}
			$data = db("student")->where($where)->join("myclass","student.classid=myclass.id")->field("student.*,myclass.classname")->select();
			foreach ($data as $key => &$value) {
				$sign = db("sign")->where("studentid=".$value["id"]."  and to_days(sign.signdate) = to_days(now()) ")->find();
				if($sign){
					$value["ischeck"]="是";
					$value["signdate"]=$sign["signdate"];
				}else{
					$value["ischeck"]="否";
				}
			}
			return json(['status'=>200,'data'=>$data]);
		}else if($type=="2"){
			$where="  sign.mid=".$mid." and to_days(sign.signdate) = to_days(now()) ";
			if($classid!=""){
				$where=$where." and sign.classid=".$classid;
			}
			$data = db('sign')->join("student","sign.studentid=student.id")->join("myclass","myclass.id=student.classid")->field("student.truename,myclass.classname,sign.signdate")->where($where)->select();
			foreach ($data as $key => &$value) {
				$value["ischeck"]="是";
			}
			return json(['status'=>200,'data'=>$data]);
		}else if($type=="3"){
			$where=" sign.mid=".$mid." and to_days(sign.signdate) = to_days(now()) and state=0";
			if($classid!=""){
				$where=$where." and sign.classid=".$classid;
			}
			$sql = 'select student.*,myclass.classname from student join myclass on  myclass.id= student.classid where student.id not in (SELECT studentid FROM sign where '.$where.') and student.mid='.$mid;
			
			$data = Db::query($sql);
			foreach ($data as $key => &$value) {
				$value["ischeck"]="否";
			}

			return json(['status'=>200,'data'=>$data]);
		}else if($type=="4"){
			$where =" to_days(leave.stime) = to_days(now()) and leave.mid=".$mid;
			if($classid!=""){
				$where=$where." and leave.classid=".$classid;
			}
			$data = db('leave')->join("student","student.id=leave.sid")->join("myclass","myclass.id=leave.classid")->field("student.truename.myclass.classname")->where($where)->select();
			foreach ($data as $key => &$value) {
				$value["ischeck"]="否";
			}

			return json(['status'=>200,'data'=>$data]);
		}

	}
	//反馈
	public function feedback(){
		$request = Request::instance();
		$data["content"] = $request->post('content');
		$data["mid"] = $request->post('mid');
	
		$data["createtime"] =  date('Y-m-d H:i:s',time());
		$data["userid"] = $request->post('userid');

		$user = db("users")->where("id=".$data["userid"])->find();
		

		if(db('feedback')->insertGetId($data)){

			$kefulist = db("users")->where("iskefu=1")->select();
			foreach ($kefulist as $key => &$value) {
				$arr=array($user["nickname"],$user["phone"],$data["createtime"],$data["content"]);
				sendtempmsg2("1j0Dwgn1Uel9HW-bsmHTTFZ9S7HF7rXTD7MKyASOBWc",$value["openid"],"",$arr);
			}

			return json(['status'=>200,'message'=>'提交成功']);
		   
	   }else{
		   return json(['status'=>500,'message'=>'提交失败']);
	   }
	}

	//检测手机号是否重复
	public function checkphone(){

		$phone = $_POST["phone"];
		$mechanism = db("mechanism")->where("phone='".$phone."'")->find();
		if($mechanism){
			return json(['status'=>500,'message'=>'联系方式重复了']);

		}else{
			return json(['status'=>200,'message'=>'success']);

		}

	}
	//用户在线
	public function useronline(){
		$userid =$_POST["userid"];
		$videoid =$_POST["videoid"];
		$onlinetime =  date('Y-m-d H:i:s',time());
		$useronline= db("useronline")->where("videoid=".$videoid." and userid=".$userid)->find();
		if($useronline){
			$updateresult = Db::execute('update useronline set onlinetime=? where id=?  ',[$onlinetime, $useronline["id"]]);
			return json(['status'=>200,'message'=>'success']);
		}else{
			$updateresult = Db::execute('insert into  useronline(userid,onlinetime,videoid) values(?,?,?) ',[$userid, $onlinetime,$videoid]);
			return json(['status'=>200,'message'=>'success']);
		}
	}
}
